/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.cmd;

import com.google.common.base.Joiner;
import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.core.model.FlowElement;
import com.je.bpm.core.model.config.task.TaskDelayConfigImpl;
import com.je.bpm.core.model.task.KaiteBaseUserTask;
import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.impl.interceptor.Command;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.DelayLogEntity;
import com.je.bpm.engine.impl.persistence.entity.DelayLogEntityImpl;
import com.je.bpm.engine.impl.persistence.entity.TaskEntity;
import org.apache.commons.lang3.time.DateFormatUtils;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * 延迟命令
 */
public class DelayCmd implements Command<Void>, Serializable {

    private static final String DELAY_DESC_FORMT = "任务【%s】由【%s】延期，下次处理截止时间为【%s】。";

    private String taskId;

    private Date nextDueDate;

    private List<String> users;

    public DelayCmd(String taskId) {
        this.taskId = taskId;
    }

    public DelayCmd(String taskId, Date nextDueDate) {
        this.taskId = taskId;
        this.nextDueDate = nextDueDate;
    }

    public DelayCmd(String taskId, List<String> users) {
        this.taskId = taskId;
        this.users = users;
    }

    public DelayCmd(String taskId, Date nextDueDate, List<String> users) {
        this.taskId = taskId;
        this.nextDueDate = nextDueDate;
        this.users = users;
    }

    @Override
    public Void execute(CommandContext commandContext) {
        TaskEntity task = commandContext.getProcessEngineConfiguration().getTaskEntityManager().findById(taskId);
        if(task == null){
            throw new ActivitiException(String.format("Can not find the task %s.",taskId));
        }

        BpmnModel bpmnModel = commandContext.getProcessEngineConfiguration().getRepositoryService().getBpmnModel(task.getProcessDefinitionId());
        FlowElement flowElement = bpmnModel.getFlowElement(task.getTaskDefinitionKey());
        if(flowElement == null){
            throw new ActivitiException("Can't find the flow element from the process definition.");
        }
        if(!(flowElement instanceof KaiteBaseUserTask)){
            throw new ActivitiException("Can't delay on this type task.");
        }


        Date dueTime = task.getDueDate() == null?new Date():task.getDueDate();
        String assignee = task.getAssignee();
        if(nextDueDate == null){
        }
        task.setDueDate(nextDueDate);
        commandContext.getProcessEngineConfiguration().getTaskEntityManager().update(task);

        String receiver = users == null?null:Joiner.on(",").join(users);
        DelayLogEntity delayLogEntity = new DelayLogEntityImpl();
        delayLogEntity.setCreateTime(new Date());
        delayLogEntity.setAssignee(receiver);
        delayLogEntity.setDescription(String.format(DELAY_DESC_FORMT,task.getName(),assignee, DateFormatUtils.format(nextDueDate,"yyyy-MM-dd HH:mm:ss")));
        delayLogEntity.setProcessDefinitionId(task.getProcessDefinitionId());
        delayLogEntity.setProcessInstanceId(task.getProcessInstanceId());
        delayLogEntity.setDueTime(nextDueDate);
        delayLogEntity.setTaskId(taskId);
        delayLogEntity.setTaskName(task.getName());
        commandContext.getProcessEngineConfiguration().getDelayLogEntityManager().insert(delayLogEntity);
        return null;
    }

}
